import cv2
import numpy as np
import matplotlib.pyplot as plt
from math import sqrt
from xml.dom.minidom import parse
import pytesseract
import os


def takeElementDixian(l):
    return l[0][0][1][0]


def takeElementLeftlow(l):
    return l[0][0][1]


# 对All_cell_points筛选以及重新排序

def sort_All_cell_points(All_cell_points):
    """
    该函数作用：以单元格底线为排序基准对All_cell_points进行重新排序
    :param All_cell_points: 解析表格结构得到的单元格的位置信息，按其表格结构信息中的行（row）记录
    :return:All_cell_low， 重新排序后的单元格， 单元格row col两个方向均实现了从小到大的排序
    """
    # 以单元格的底线为基准
    # 收集所有单元格的底线值
    low_cell_pre = 0
    low_cell_list = []
    for row in All_cell_points:
        for cell in row:
            low_cell = cell[1][0]
            # print(cell)
            if low_cell in low_cell_list:
                continue
            low_cell_list.append(low_cell)

    All_cell_low = []
    for low in low_cell_list:

        cells = []
        # 遍历所有的单元格寻找底线相同的单元格
        index = 0

        for index_row, row in enumerate(All_cell_points):

            for index_cell, cell in enumerate(row):

                # print(cell)
                if not cell:
                    continue

                low_cell = cell[1][0]

                if low_cell == low:
                    cells.append([cell, [index_row, index_cell], index])
                index = index + 1

        All_cell_low.append(cells)

    All_cell_low.sort(key=takeElementDixian)
    l = []
    for cells in All_cell_low:
        cells.sort(key=takeElementLeftlow)
        l.append(cells)
    All_cell_low = l
    return All_cell_low
